//package com.pp.tourism.gateway.service;
//
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
//import org.springframework.cloud.gateway.route.RouteDefinition;
//import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
//import org.springframework.cloud.gateway.support.NotFoundException;
//import org.springframework.context.ApplicationEventPublisher;
//import org.springframework.context.ApplicationEventPublisherAware;
//import org.springframework.http.ResponseEntity;
//import org.springframework.stereotype.Service;
//import reactor.core.publisher.Mono;
//
//@Service
//public class DynamicRouteServiceImpl implements ApplicationEventPublisherAware {
//
//    @Autowired
//    private RouteDefinitionWriter routeDefinitionWriter;
//    private ApplicationEventPublisher applicationEventPublisher;
//
//    /**
//     * 增加路由
//     *
//     * @param routeDefinition
//     * @return
//     */
//    public String addRoute(RouteDefinition routeDefinition) {
//        routeDefinitionWriter.save(Mono.just(routeDefinition)).subscribe();
//        applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this));
//        return "success";
//    }
//
//    /**
//     * 更新路由
//     *
//     * @param routeDefinition
//     * @return
//     */
//    public String updateRoute(RouteDefinition routeDefinition) {
//        try {
//            routeDefinitionWriter.delete(Mono.just(routeDefinition.getId()));
//        } catch (Exception e) {
//            return "update fail,not find route  routeId: " + routeDefinition.getId();
//        }
//        try {
//            return addRoute(routeDefinition);
//        } catch (Exception e) {
//            return "update route  fail";
//        }
//    }
//
//    /**
//     * 删除路由
//     *
//     * @param id
//     * @return
//     */
//    public Mono<ResponseEntity<Object>> deleteRoute(String id) {
//        return routeDefinitionWriter.delete(Mono.just(id)).then(Mono.defer(() -> Mono.just(ResponseEntity.ok().build()))).onErrorResume(t -> t instanceof NotFoundException, t -> Mono.just(ResponseEntity.notFound().build()));
//    }
//
//    @Override
//    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
//        this.applicationEventPublisher = applicationEventPublisher;
//    }
//}
